<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css">
<script>
var gmailLabel = ["_● to me", ""];

var gmailUrl = [
  "https://mail.google.com/a/google.com/#label/_%E2%97%8F+to+me",
  "https://mail.google.com/"
];

// The first AtomRef was to be https://mail.google.com/a/google.com/feed/atom",
// but this link was forbidden (error 403), so we have to parse the html.
var gmailAtomRef = [
  "https://mail.google.com/a/google.com/h/",
  "https://mail.google.com/mail/feed/atom"
];

var unreadGmailCount = ["x", "x"];
var xhrGmail = [new XMLHttpRequest(), new XMLHttpRequest()];

var pollInterval = 1000 * 60;  // 1 minute
var requestTimeout = 1000 * 10;  // 10 seconds

var scheduledTimerId;

function init() {
  startRequest();
  window.setInterval(startRequest, pollInterval);
}

function startRequest() {
  for (var i = 0; i < gmailAtomRef.length; ++i) {
    getGmailCount(i, updateGmailCount);
  }
}

function getGmailCount(index, startUpdate) {
  var xhr = xhrGmail[index];

  var abortTimerId = window.setTimeout(function() {
    xhr.abort();
    startUpdate(index, "x");
    console.log("timeout, index:" + index);
  }, requestTimeout);

  function handleSuccess(index, count) {
    window.clearTimeout(abortTimerId);
    startUpdate(index, count);
  }

  function handleError(index) {
    window.clearTimeout(abortTimerId);
    startUpdate(index, "x");
  }

  try {
    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        var fullCount = "x";
        if (gmailAtomRef[index].indexOf("feed/atom") != -1) {
          fullCount = parseNormalGmail(xhr.responseXML);
        } else {
          fullCount = parsePrivateGmail(xhr.responseText, gmailLabel[index]);
        }
        handleSuccess(index, fullCount);
      }
    }

    xhr.onerror = function(error) {
      console.log("request error, index:" + index);
      handleError(index);
    }

    xhr.abort();
    xhr.open("GET", gmailAtomRef[index], true);
    xhr.send(null);
  } catch(e) {
    console.log("exception: " + e + ", index:" + index);
    handleError(index);
  }
}

function parseNormalGmail(xmlDoc) {
  if (xmlDoc) {
    var fullCountSet = xmlDoc.evaluate("/gmail:feed/gmail:fullcount",
    xmlDoc, gmailNSResolver, XPathResult.ANY_TYPE, null);
    var fullCountNode = fullCountSet.iterateNext();
    if (fullCountNode) {
      return fullCountNode.textContent;
    }
  }
  return "x";
}

function parsePrivateGmail(text, label) {
  var fullCount = "x";
  var pos = text.indexOf(label);
  if (pos != -1) {
    pos += label.length;
    if (text.substring(pos, pos + 6) == "&nbsp;") {
      pos += 6;
    }
    var subtext = text.substring(pos, pos + 10);
    if (subtext[0] == "(" && subtext.indexOf(")") != -1) {
      fullCount = subtext.substring(1, subtext.indexOf(")"));
    } else {
      fullCount = "0";
    }
  }
  return fullCount;
}

function gmailNSResolver(prefix) {
  if(prefix == 'gmail') {
    return 'http://purl.org/atom/ns#';
  }
}

// ui stuff
function updateGmailCount(index, count) {
  if (unreadGmailCount[index] != count) {
    unreadGmailCount[index] = count;
    startGmailFlip(index);
  }
}

function goToGmailInbox(index) {
  chrome.tabs.create({url: gmailUrl[index]});
}

// animation
function startGmailFlip(index) {
  document.getElementById("unreadGmailCount" + index).className = 'mid-flip';
  setTimeout("midGmailFlip(" + index + ")", 500);
}

function midGmailFlip(index) {
  document.getElementById("unreadGmailCount" + index).className = 'post-flip';
  document.getElementById("unreadGmailCount" + index).innerHTML =
    "(" + unreadGmailCount[index] + ")";
  setTimeout("endGmailFlip(" + index + ")", 500);
}

function endGmailFlip(index) {
  document.getElementById("unreadGmailCount" + index).className = 'base-flip';
}

</script>
</head>
<body onload="init()">
  <div class="toolstrip-button" onclick="goToGmailInbox(0)">
    <img src="gmail0.png" style="width:auto; height:auto">
    <span style="display: inline-block;" id="unreadGmailCount0" class="base-flip">(?)</span>
  </div>
  <div class="toolstrip-button" onclick="goToGmailInbox(1)">
    <img src="gmail1.png" style="width:auto; height:auto">
    <span style="display: inline-block;" id="unreadGmailCount1" class="base-flip">(?)</span>
  </div>
</body>
</html>
